from pytc import BDB, BDBOREADER
import sys

class ReaderDbTcIndexer(object):
    def __init__(self, filename, cache=0):
        self.db = BDB()
        #self.db.setcache(cache)
        self.db.open(filename, BDBOREADER)
        self.edges_k='edges_'
        self.size = len(self.db.rangefwm(self.edges_k,-1))
        self.delta=1

    def __del__(self):
        self.db.close()
    
    def __getitem__(self, item):
        item_str = str(item+self.delta)
        key = self.edges_k+item_str
        if not self.db.has_key(key):
            print "%s\t%s\t%s"%(item,self.delta,self.size)
            self.delta+=1
            try:
                return self.__getitem__(item)
            except:
                sys.exit()
        else:
            return [ int(n) for n in self.db.get(key)]

    def __len__(self):
        return self.size

def initAV(keys):
    av = [0 for _ in keys]
    return av

def pageRank(adjl, alpha, maxiter):
    #keys = adjl.keys()
    keys = range(len(adjl))
    av_base = initAV(adjl)
    av = initAV(adjl)
    n = len(keys)
    neighbors_size = {}
    for j in keys:
        neighbors_size[j] = len(adjl[j])
    print "Acquired neighbors size"
    for it in xrange(maxiter):
        ps = 1-alpha
        av_next= initAV(keys)

        for j in keys:
            m = neighbors_size[j]
            if m == 0:
                ps+=alpha*av[j]
            else:
                neighbors = adjl[j]                
                for k in neighbors:
                    av_next[k]+=alpha*(av[j]/m) 

                    

        norm=0.0
        psn=ps/n
        for j in keys:
            av_next[j]+=psn
            norm+=av_next[j]
        for j in keys:
                av_next[j]/=norm

        av = av_next

    return av

db = ReaderDbTcIndexer('db.tcb', 10000)

pageRank(db, 0.85, 1)
